package com.yuedou.jylt.manager;

import android.app.Presentation;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.yuedou.jylt.R;
import com.yuedou.jylt.adapter.ChangeBanner;
import com.yuedou.jylt.adapter.MediaVideoBannerAdapter;
import com.yuedou.jylt.bean.DeviceMaterialBean;
import com.yuedou.jylt.bean.ResourceBean;
import com.yuedou.jylt.utils.FileOper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class DifferentDisplay extends Presentation {


    @BindView(R.id.banner_video_other)
    ChangeBanner bannerOther;

    Context context;
    private MediaPlayer mediaPlayer = null;

    private List<ResourceBean> dataList = new ArrayList<>();
    private MediaVideoBannerAdapter mAdapter;
    private BannerVideoManager mBannerVideoManager;

    public DifferentDisplay(Context outerContext, Display display) {
        super(outerContext,display);
        context = outerContext;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_seccond_screen_banner);



        initLocalFileList();
        mAdapter = new MediaVideoBannerAdapter(context, dataList);
        bannerOther = findViewById(R.id.banner_video_other);
        bannerOther.isAutoLoop(true);
        bannerOther.setAdapter(mAdapter).
                setIndicator(new CircleIndicator(context))
                .setIndicatorGravity(IndicatorConfig.Direction.CENTER);
        mBannerVideoManager = new BannerVideoManager(context, bannerOther, mAdapter, dataList);
        mBannerVideoManager.setPageChangeMillis(10000);
        mBannerVideoManager.setVideoPlayLoadWait(10000);

//        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
//        } else {
////            initMediaPlayer();//初始化MediaPlayer
//        }
    }


    /**
     *  重新获取 当前轮播图片
     */
    private void initLocalFileList(){
        dataList = new ArrayList<>();

        List<DeviceMaterialBean> materials = new ArrayList<>();
        DeviceMaterialBean materialBean1 = new DeviceMaterialBean();
        materialBean1.setFileType("PNG");
        materialBean1.setCreateTime(new Date());
        materialBean1.setImgUrl("https://api.sdyuedou.com/ydimg/lunbo/other/other_banner_1.png");
        materialBean1.setDeviceId(0);
        materialBean1.setSort(0);
        materialBean1.setIsCommon(0);
        materialBean1.setState(1);
        materialBean1.setVersion("other");


        DeviceMaterialBean materialBean2 = new DeviceMaterialBean();
        materialBean2.setFileType("PNG");
        materialBean2.setCreateTime(new Date());
        materialBean2.setImgUrl("https://api.sdyuedou.com/ydimg/lunbo/other/other_banner_2.png");
        materialBean2.setDeviceId(0);
        materialBean2.setSort(0);
        materialBean2.setIsCommon(0);
        materialBean2.setState(1);
        materialBean2.setVersion("other");


        DeviceMaterialBean materialBean3 = new DeviceMaterialBean();
        materialBean3.setFileType("PNG");
        materialBean3.setCreateTime(new Date());
        materialBean3.setImgUrl("https://api.sdyuedou.com/ydimg/lunbo/other/other_banner_3.png");
        materialBean3.setDeviceId(0);
        materialBean3.setSort(0);
        materialBean3.setIsCommon(0);
        materialBean3.setState(1);
        materialBean3.setVersion("other");

        materials.add(materialBean1);
        materials.add(materialBean2);
        materials.add(materialBean3);


        try{
            int imgCount = 0;
            for (DeviceMaterialBean matrailBean: materials){
                System.out.println("imgUrl:" + matrailBean.getImgUrl());
                Glide.with(context).downloadOnly().load(matrailBean.getImgUrl())
                        .listener(new RequestListener<File>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
//                                        Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
//                                        Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                                FileOper.saveFileByDownload(resource, matrailBean.getImgUrl(), "other");
                                return false;
                            }
                        }).preload();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

//        this.version = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION);
//        System.out.println("广告版本号：" + this.version);
        String directory = Environment.getExternalStorageDirectory().toString() + "/material/other";
        List<String> imgs = getFilesAllName(directory);
        if(imgs != null && imgs.size() > 0){
            System.out.println("imgs: " + imgs.toString());
            for (String img : imgs){
                ResourceBean resourceBean = new ResourceBean();
                resourceBean.setType(1);
                resourceBean.setUrl("file://"+ img);
                dataList.add(resourceBean);
            }
            if(mBannerVideoManager!=null){
                mBannerVideoManager.resetList(dataList);
            }
        }
    }


    public static List<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null){
            Log.e("error","空目录");
            return null;
        }
        List<String> s = new ArrayList<>();
        for(int i = 0;i < files.length;i++){
            s.add(files[i].getAbsolutePath());
            System.out.println("");
        }
        return s;
    }

    /**
     * 播放音频文件
     */
    private void initMediaPlayer(){
        try {
            mediaPlayer = new MediaPlayer();
            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.open_video);
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    System.out.println("播放========");
                    if(mediaPlayer.isPlaying()){
                        System.out.println("播放停止========");
//                        mediaPlayer.stop();//开始播放开箱成功
                        stopPlay();
                    }
                }
            });

            //设置出错的监听器
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    //提示用户
                    stopPlay();
                    //释放播放器
                    return true;
                }
            });
//            mediaPlayer.setDataSource(file.getPath());//指定音频文件的路径
            mediaPlayer.prepare();//让MediaPlayer进入到准备状态
            mediaPlayer.setVolume(1f, 1f);;//开始播放开箱成功
            mediaPlayer.setLooping(false);
            mediaPlayer.start();//开始播放开箱成功
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
                mediaPlayer = null;
                mediaPlayer = new MediaPlayer();
                mediaPlayer.stop();
            }

            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

}